package org.wuyichun.gift.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.wuyichun.gift.client.LoginUserFeignClient;
import org.wuyichun.gift.domain.LoginUser;
import org.wuyichun.gift.domain.User;
import org.wuyichun.gift.dto.UserRegisterDto;
import org.wuyichun.gift.exception.BusinessException;
import org.wuyichun.gift.mapper.UserMapper;
import org.wuyichun.gift.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.wuyichun.gift.syscode.SystemErrorCode;
import org.wuyichun.gift.util.AjaxResult;
import org.wuyichun.gift.util.BitStatesUtils;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author wuyichun
 * @since 2024-09-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;


    @Autowired
    private LoginUserFeignClient loginUserFeignClient;
    /*
        1.做参数的校验  [非空,格式]
        2.验证手机验证码是否正确
        3.准备封装保存的对象
            User
            认证中心 LoginUser
        4.保存数据
            4.1 发起远程调用  -->先保存认证中心数据 -->返回主键id
            4.2 保存本地数据  -->完成数据的填充

     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void register(UserRegisterDto dto) {
        //进行数据的校验
        checkData(dto);
        //数据的封装
        User user = userBean(dto);
        //发起远程调用
        LoginUser loginUser = loginUserBean(user);
        AjaxResult ajaxResult = loginUserFeignClient.addOrUpdate(loginUser);
        if (ajaxResult.isSuccess()) {
            Object idObj = ajaxResult.getResultObj();
            user.setLoginId(Long.valueOf(idObj.toString()));
        }
        super.insert(user);
    }

    private LoginUser loginUserBean(User user) {
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user,loginUser);
        loginUser.setUsername(user.getPhone());
        loginUser.setType(LoginUser.USER_WEBSITE);
        return loginUser;
    }

    private User userBean(UserRegisterDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        user.setPassword(DigestUtil.md5Hex(salt+dto.getPassword()));
        user.setCreateTime(new Date().getTime());
        //给用户添加状态
        long l = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        long state = BitStatesUtils.addState(l, BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(state);
        return user;
    }


    private void checkData(UserRegisterDto dto) {
        //System.out.println(1/0);
        //1.验证手机号非空,并且是一个手机号
//        if (StringUtils.isBlank(dto.getPhone())) {
//           // throw new RuntimeException("手机号不能为空");
//            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_400);
//        }
        //2.验证手机号是个手机号
//        if (!dto.getPhone().matches("^1[3-9]\\\\d{9}$")) {
//            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_400);
//        }
//        if (StringUtils.isBlank(dto.getPassword())) {
//            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_400);
//        }
//        if (StringUtils.isBlank(dto.getPhoneCode())) {
//            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_400);
//        }

        String key = dto.getType()+":"+dto.getPhone();
        //验证码的正确性校验
        // 8527:169416556161
        Object o = redisTemplate.opsForValue().get(key);

        if (o==null){
            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_200002);
        }
        if (!o.toString().split(":")[0].equals(dto.getPhoneCode())) {
            throw new BusinessException(SystemErrorCode.RESPONSE_CODE_200002);
        }

    }
}
